package com.scau.phr.sdk.baiduMap;

import com.scau.phr.business.hosipital.controller.HospitalController;
import com.scau.phr.business.hosipital.service.HospitalService;
import com.scau.phr.domain.entity.Hospital;
import com.scau.phr.domain.entity.Newhospital;
import com.scau.phr.sdk.baiduMap.domain.HospitalCoordinate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 根据两个地点的经纬度计算地点的距离
 * 根据一个地址，计算离他最近的医院地址
 * Created with IDEA
 * author:scaurb
 * Date:2018/8/10/010
 * Time:9:41
 **/
@Component
public class MyAddressUtil {

    //半径，单位为千米
    private static final double Radius = 6378.140;
    private static final double pi = 3.14159265358979323846;

    @Autowired
    private HospitalService hospitalService;

    public List<HospitalCoordinate> getNearHospital(String city, double longitude, double latitude){
        List<HospitalCoordinate> result = new ArrayList<>();
        //List<Newhospital> list = hospitalService.getHospitalLocation("广东省","潮州市");
        //根据省跟市拉取医院
        //List<Newhospital> list = hospitalService.getHospitalLocation(province,city);
        //根据市拉取医院
        List<Newhospital> list = hospitalService.getHospitalLocation2(city);
        for (Newhospital item: list) {
            //System.out.println(item.getAddress());
            double itemLongitude = item.getLongitude();
            double itemLatitude = item.getLatitude();
            HospitalCoordinate hospital = new HospitalCoordinate();
            hospital.setLatitude(itemLatitude);
            hospital.setLongitude(itemLongitude);
            //计算dist
            hospital.setDist(calc(longitude,latitude,itemLongitude,itemLatitude));
            result.add(hospital);
        }

        Collections.sort(result);
        result = result.subList(0,10);

        return result;
    }

    /**
     * 根据经纬度计算距离
     * C = sin(MLatA)*sin(MLatB)*cos(MLonA-MLonB) + cos(MLatA)*cos(MLatB)
     *  Distance = R*Arccos(C)*Pi/180
     * @param MLonA
     * @param MLatA
     * @param MLonB
     * @param MLatB
     * @return
     */
    private double calc(double MLonA,double MLatA,double MLonB,double MLatB){
        double C = Math.sin(MLatA) * Math.sin(MLatB)*Math.cos(MLonA-MLonB) + Math.cos(MLatA)*Math.cos(MLatB);
        double Distance = Radius * Math.acos(C)*pi/180;
        return Distance;
    }

}
